package org.jeecg.modules.flowable.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.flowable.controller.dto.FlowStartRequest;
import org.jeecg.modules.flowable.demo.dto.DemoBizDTO;
import org.jeecg.modules.flowable.demo.entity.DemoBizEntity;
import org.jeecg.modules.flowable.demo.mapper.DemoBizMapper;
import org.jeecg.modules.flowable.demo.service.DemoBizService;
import org.jeecg.modules.flowable.service.MatterService;
import org.jeecg.modules.flowable.service.bo.flow.FlowInst;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * 流程引擎demo示例
 *
 * @author jiangtianyi
 */
@Service
public class DemoBizServiceImpl implements DemoBizService {

    private final MatterService matterService;

    private final DemoBizMapper demoBizMapper;

    @Override
    public List<DemoBizEntity> queryAll() {
        // 组装查询条件
        QueryWrapper<DemoBizEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("CREATE_TIME");

        // 登录用户信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        wrapper.eq("CREATE_BY", loginUser.getUsername());

        return demoBizMapper.selectList(wrapper);
    }

    @Override
    public DemoBizEntity queryOne(String id) {
        return demoBizMapper.selectById(id);
    }

    @Override
    public void delete(String id) {
        demoBizMapper.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(DemoBizDTO demoBizDTO) {
        FlowStartRequest flowStartRequest = new FlowStartRequest();
        flowStartRequest.setMatterId(demoBizDTO.getFlowInstanceId());
        flowStartRequest.setTitle(demoBizDTO.getTitle());
        flowStartRequest.setFormKey(demoBizDTO.getFormKey());
        flowStartRequest.setFormContent(demoBizDTO.getFormContent());
        // 启动流程
        FlowInst flowInst = matterService.flowStart(flowStartRequest);

        DemoBizEntity demoBizEntity = new DemoBizEntity();
        BeanUtils.copyProperties(demoBizDTO, demoBizEntity);
        demoBizEntity.setId(UUID.randomUUID().toString());
        demoBizEntity.setMatterInstId(flowInst.getMatterInst());
        demoBizMapper.insert(demoBizEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(DemoBizEntity demoBizEntity) {
        demoBizMapper.updateById(demoBizEntity);
    }

    public DemoBizServiceImpl(MatterService matterService, DemoBizMapper demoBizMapper) {
        this.matterService = matterService;
        this.demoBizMapper = demoBizMapper;
    }
}
